<?php
namespace app\lib\aliyun;

use think\Db;
use app\model\UserBill as UserBillModel;
use app\model\Bill as BillModel;
use app\model\User as UserModel;
use app\model\Order as OrderModel;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

use AlibabaCloud\SDK\BssOpenApi\V20171214\BssOpenApi;
use AlibabaCloud\SDK\Sts\V20150401\Sts;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\CreateAgAccountRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\DescribeInstanceBillRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\GetOrderDetailRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\QueryProductListRequest;
use AlibabaCloud\SDK\Sts\V20150401\Models\AssumeRoleRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\QueryOrdersRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\CancelOrderRequest;

use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\CreateResellerUserQuotaRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\QueryResellerAvailableQuotaRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\SetResellerUserQuotaRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\GetCustomerAccountInfoRequest;
use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\SetResellerUserStatusRequest;

use AlibabaCloud\SDK\BssOpenApi\V20171214\Models\ChangeResellerConsumeAmountRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;


class Api 
{

    public function resetUserQuota(){
        $list = Db::name('user')->where([
            ['total_recharge','>',0],
            ['is_quota','=',1]
        ])->select();
        foreach ($list as $k => $vo) {
            $this->SetResellerUserQuota($vo['pk']);
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return BssOpenApi Client
     */
    public static function createClient($accessKeyId='',$accessKeySecret=''){
        $config = config('config.alibabacloud');
        if (empty($accessKeyId)) {
            $accessKeyId = $config['keyId'];
        }
        if (empty($accessKeySecret)) {
            $accessKeySecret = $config['keySecret'];
        }
        $aliconfig = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $aliconfig->endpoint = "business.aliyuncs.com";
        return new BssOpenApi($aliconfig);
    }

    // 使用AK&SK初始化账号Client
    public static function accessKeyClient($accessKeyId='',$accessKeySecret=''){
        $config = config('config.alibabacloud');
        if (empty($accessKeyId)) {
            $accessKeyId = $config['keyId'];
        }
        if (empty($accessKeySecret)) {
            $accessKeySecret = $config['keySecret'];
        }
        $regionid = 'cn-beijing';

        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId($regionid)->asDefaultClient();
    }

    /**
     * ===================================================================================
     * ======================================角色扮演======================================
     */
    
    // 扮演RAM角色
    public function AssumeRole($ower_id){
        try {
            $user = UserModel::field('id,pk,role_name,mobile')->where('pk',$ower_id)->find();
            if (empty($user)) {
                return ['status'=>0,'msg'=>'用户不存在'];
            }
            $config = config('config.aliasssume');
            $aliconfig = new Config([
                "accessKeyId" => $config['keyId'],
                "accessKeySecret" => $config['keySecret']
            ]);
            // 访问的域名
            $aliconfig->endpoint = "sts.cn-beijing.aliyuncs.com";
            $client = new Sts($aliconfig);
            $assumeRoleRequest = new AssumeRoleRequest([
                "roleArn" => "acs:ram::".$user['pk'].":role/".$user['role_name'],
                "roleSessionName" => 'user_'.$user['mobile']
            ]);

            $result = $client->assumeRole($assumeRoleRequest);
            $result = $result->body->toMap();
            return ['status'=>1,'data'=>[
                'AccessKeyId'=>$result['Credentials']['AccessKeyId'],
                'AccessKeySecret'=>$result['Credentials']['AccessKeySecret'],
                'SecurityToken'=>$result['Credentials']['SecurityToken']
            ]];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 获取登录令牌
    public function GetSigninToken($ower_id){
        $credentials = $this->AssumeRole($ower_id);
        if ($credentials['status'] == 0) {
            return $credentials;
        }
        $credentials = $credentials['data'];

        // SK初始化账号Client
        self::accessKeyClient($credentials['AccessKeyId'], $credentials['AccessKeySecret']);
        $options = [
            'TicketType' => 'mini',
            'AccessKeyId'=>$credentials['AccessKeyId'],
            'AccessKeySecret'=>$credentials['AccessKeySecret'],
            'SecurityToken'=>$credentials['SecurityToken']
        ];
        try {
            $result = AlibabaCloud::rpc()
                      // ->product('federation')
                      ->version('2015-04-01')
                      ->action('GetSigninToken')
                      ->method('POST')
                      ->host('signin.aliyun.com/federation')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            if (!empty($result['SigninToken'])) {
                $result = ['status'=>1,'data'=>$result['SigninToken']];
            }else{
                $result = ['status'=>0,'msg'=>$result['Message']];
            }
        } catch (ClientException $e) {
            $result = ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            $result = ['status'=>0,'msg'=>$e->getMessage()];
        }
        return $result;
    }

    /**
     * ===================================================================================
     * ======================================账号管理======================================
     */

    // 创建平行账号
    public function CreateAgAccount($id){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] != 0) {
            return apiErrorResult('当前用户已同步');
        }
        
        $options = [
          'LoginEmail' => $uinfo['email'],
          'AccountAttr' => $uinfo['account_attr'],
          'EnterpriseName' => $uinfo['enterprise'],
          'FirstName' => $uinfo['first_name'],
          'LastName' => $uinfo['last_name'],
          'NationCode' => $uinfo['nation'],
          'ProvinceName' => $uinfo['province'],
          'CityName' => $uinfo['city'],
          'Postcode' => $uinfo['zip_code']
        ];
        $options = delEmpty($options);

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                      ->product('BssOpenApi')
                      ->scheme('https')
                      ->version('2017-12-14')
                      ->action('CreateAgAccount')
                      ->method('POST')
                      ->host('business.aliyuncs.com')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            if ($result['Code'] != 'SUCCESS') {
                return apiErrorResult($result['Message']);
            }
            Db::name('user')->where('id',$id)->update([
                'status'=>1,
                'pk'=>$result['AgRelationDto']['Pk'],
                'type'=>$result['AgRelationDto']['Type'],
                'role_name'=>$result['AgRelationDto']['RamAdminRoleName'],
                'utime'=>time()
            ]);

            // 创建用户 Quota 配额账本
            $this->CreateResellerUserQuota($result['AgRelationDto']['Pk']);

            return apiSuccessResult('同步成功');
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    // 查找虚商客户账号信息
    public function GetCustomerAccountInfo($ower_id){
        try {
            $client = self::createClient();
            $getCustomerAccountInfoRequest = new GetCustomerAccountInfoRequest([
                'ownerId'=>$ower_id
            ]);
            $result = $client->getCustomerAccountInfo($getCustomerAccountInfoRequest);
            $result = $result->body->toMap();
            return $result;
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 实名认证
    public function AddIdentityCertifiedForBidUser($id){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT', // NORMAL普通虚商（默认值）,多半这个是贝多的权限
            'PK' => $uinfo['pk'],
            'Phone' => $uinfo['mobile'],
            'Name' => $uinfo['name'],
            'LicenseType' => $uinfo['license_type'],
            'LicenseNumber' => $uinfo['license_number'],
            'IsEnterprise' => $uinfo['account_attr'] == 1
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                      ->version('2015-04-08')
                      ->action('AddIdentityCertifiedForBidUser')
                      ->method('POST')
                      ->host('crm-cn-hangzhou.aliyuncs.com')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            // 认证成功只会返回RequestId，如果有Code说明有错误
            if (isset($result['Code'])) {
                return apiErrorResult($result['Message']);
            }
            Db::name('user')->where('id',$id)->update([
                'status'=>2,
                'utime'=>time()
            ]);
            
            return apiSuccessResult('实名认证成功');
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            // 如果返回的错误是已实名认证，则视为认证成功
            if (strpos($e->getMessage(), 'Already Certified') !== false) {
                Db::name('user')->where('id',$id)->update([
                    'status'=>2,
                    'utime'=>time()
                ]);
                return apiSuccessResult('实名认证成功');
            }else{
                return apiErrorResult($e->getMessage());    
            }
        }
    }

    // 删除实名认证信息
    public function RemoveIdentityCertifiedForBidUser($id=''){
        $uinfo = Db::name('user')->where('id',$id)->find();
        if ($uinfo['status'] != 2) {
            return apiErrorResult('用户暂未实名');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT',
            'PK' => $uinfo['pk']
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                ->version('2015-04-08')
                ->action('RemoveIdentityCertifiedForBidUser')
                ->method('POST')
                ->host('crm-cn-hangzhou.aliyuncs.com')
                ->options(['query' => $options])
                ->request();
            $result = $result->toArray();
            // 认证成功只会返回RequestId，如果有Code说明有错误
            if (isset($result['Code'])) {
                return apiErrorResult($result['Message']);
            }
            Db::name('user')->where('id',$id)->update([
                'status'=>1,
                'utime'=>time()
            ]);
            return apiSuccessResult('删除实名认证成功');
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            return apiErrorResult($e->getMessage());
        }
    }

    /**
     * ===================================================================================
     * ======================================预算管理======================================
     */

    // 查询当前可用配额余额信息
    public function QueryResellerAvailableQuota($ower_id){
        $client = self::createClient();
        $queryResellerAvailableQuotaRequest = new QueryResellerAvailableQuotaRequest([
            'ownerId'=>$ower_id
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->queryResellerAvailableQuota($queryResellerAvailableQuotaRequest);
        $result = $result->body->toMap();
        return $result;
    }

    // 创建用户 Quota 配额账本
    // public function CreateResellerUserQuota($id){
    //     $uinfo = Db::name('user')->where('id',$id)->find();
    //     if ($uinfo['status'] == 0) {
    //         return apiErrorResult('用户需先同步');
    //     }
    //     if ($uinfo['is_quota'] == 1) {
    //         // return apiErrorResult('当前用户已有账本');
    //     }

    //     $client = self::createClient();
    //     $createResellerUserQuotaRequest = new CreateResellerUserQuotaRequest([
    //         'ownerId'=>$uinfo['pk'],
    //         "amount" => '100',
    //         "currency" => "CNY"
    //     ]);
     
    //     $result = $client->createResellerUserQuota($createResellerUserQuotaRequest);
    //     $result = $result->body->toMap();
    //     dump($result);die;

   
    //     try {
    //         self::accessKeyClient(); // 使用AK&SK初始化账号Client
    //         $result = AlibabaCloud::rpc()
    //             ->product('BssOpenApi')
    //             // ->scheme('https') // https | http
    //             ->version('2017-12-14')
    //             ->action('CreateResellerUserQuota')
    //             ->method('POST')
    //             ->host('business.aliyuncs.com')
    //             ->options(['query' => $options])
    //             ->request();

    //         $result = $result->toArray();
    //         if (!$result['Success']) {
    //             return apiErrorResult($result['Message']);
    //         }
    //         Db::name('user')->where('id',$id)->update([
    //             'is_quota'=>1,
    //             'utime'=>time()
    //         ]);
    //         return apiSuccessResult('账本创建成功');
    //     } catch (ClientException $e) {
    //         return apiErrorResult($e->getMessage());
    //     } catch (ServerException $e) {
    //         return apiErrorResult($e->getMessage());
    //     }
    // }
    public function CreateResellerUserQuota($ower_id){
        $uinfo = UserModel::where('pk',$ower_id)->find();
        // if ($uinfo['status'] != 2) {
        //     return apiErrorResult('用户需先实名');
        // }
        if ($uinfo['is_quota'] == 1) {
            return apiErrorResult('当前用户已有账本');
        }

        $options = [
            'OwnerId' => $uinfo['pk'],
            'Amount' => round($uinfo['total_recharge']/$uinfo['total_discount'],2),
            'Currency' => 'CNY'
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                ->product('BssOpenApi')
                // ->scheme('https') // https | http
                ->version('2017-12-14')
                ->action('CreateResellerUserQuota')
                ->method('POST')
                ->host('business.aliyuncs.com')
                ->options(['query' => $options])
                ->request();

            $result = $result->toArray();
            if (!$result['Success']) {
                return apiErrorResult($result['Message']);
            }
            Db::name('user')->where('id',$uinfo['id'])->update([
                'is_quota'=>1,
                'bill_date'=>date('Ymd'),
                'utime'=>time()
            ]);
            // return apiSuccessResult('账本创建成功');
            return ['status'=>1];
        } catch (ClientException $e) {
            // return apiErrorResult($e->getMessage());
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            // return apiErrorResult($e->getMessage());
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 设置用户 Quota
    public function SetResellerUserQuota($ower_id){
        try {
            $uinfo = UserModel::field('id,pk,balance,total_recharge,total_discount,status,is_quota')->where('pk',$ower_id)->find();
            if ($uinfo['status'] == 0) {
                return apiErrorResult('用户需先同步');
            }
            if ($uinfo['is_quota'] == 0) {
                return apiErrorResult('用户需先创建账本');
            }
            $client = self::createClient();
            $amount = round($uinfo['total_recharge']/$uinfo['total_discount'],2);
            $setResellerUserQuotaRequest = new SetResellerUserQuotaRequest([
                'ownerId'=>$uinfo['pk'],
                "amount" => $amount < 0 ? 0 : $amount,
                "currency" => "CNY"
            ]);
            // dump([
            //     'ownerId'=>$uinfo['pk'],
            //     "amount" => $uinfo['balance'] < 0 ? 0 : $uinfo['balance'],
            //     "currency" => "CNY"
            // ]);die;
      
            $result = $client->setResellerUserQuota($setResellerUserQuotaRequest);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 实名认证
    public function GenerateAliyunBidCertWaysUrl($ower_id){
        $uinfo = Db::name('user')->where('pk',$ower_id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT',
            'AliyunPk' => $uinfo['pk'],
            'Platform'=>'pc',
            'SubjectType'=>'all',
            'Source'=>'BID',
            'IsOpenApp'=>true,
            'IsMobile'=>true,
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                      ->version('2015-07-01')
                      ->action('GenerateAliyunBidCertWaysUrl')
                      ->method('POST')
                      ->host('aas.aliyuncs.com')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            // 认证成功只会返回RequestId，如果有Code说明有错误
            if (isset($result['Code'])) {
                return apiErrorResult($result['Message']);
            }
            
            return apiSuccessResult('获取认证链接成功',['url'=>$result['Data']]);
        } catch (ClientException $e) {
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            // 如果返回的错误是已实名认证，则视为认证成功
            if (strpos($e->getMessage(), 'Already Certified') !== false) {
                return ['status'=>2,'msg'=>$e->getMessage()];
            }else{
                return apiErrorResult($e->getMessage());    
            }
        }
    }

    // 查询虚商客户实名认证信息
    public function QueryBidUserCertifiedInfo($ower_id){
        $uinfo = Db::name('user')->where('pk',$ower_id)->find();
        if ($uinfo['status'] == 0) {
            return apiErrorResult('用户需先同步');
        }

        $options = [
            'BidType' => 'LIGHTWEIGHT',
            'PK' => $uinfo['pk']
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                      ->version('2015-04-08')
                      ->action('QueryBidUserCertifiedInfo')
                      ->method('POST')
                      ->host('crm-cn-hangzhou.aliyuncs.com')
                      ->options(['query' => $options])
                      ->request();
            $result = $result->toArray();
            return apiSuccessResult('获取认证信息',json_decode($result['Result'],true));
        } catch (ClientException $e) {
            dump($e->getMessage());die;
            return apiErrorResult($e->getMessage());
        } catch (ServerException $e) {
            dump($e->getMessage());die;
            return apiErrorResult($e->getMessage());
        }
    }

    // 设置托管、冻结状态
    public function SetResellerUserStatus($ower_id,$business_type,$status){
        try {
            $client = self::createClient();
            $setResellerUserStatusRequest = new SetResellerUserStatusRequest([
                'ownerId'=>$ower_id,
                "status" => $status,
                "businessType" => $business_type
            ]);
            $result = $client->setResellerUserStatus($setResellerUserStatusRequest);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 用户quota消费抵扣
    // amount > 0 减少阿里侧余额，< 0 增加阿里侧余额
    public function ChangeResellerConsumeAmount($ower_id,$amount,$bill_sn){
        try {
            $client = self::createClient();
            $changeResellerConsumeAmountRequest = new ChangeResellerConsumeAmountRequest([
                'ownerId'=>$ower_id,
                "adjustType" => $amount > 0 ? "increase" : "decrease",
                "amount" => abs($amount),
                "currency" => "CNY",
                "businessType" => "quota_amount_adjust",
                "outBizId" => $bill_sn,
                "source" => "dellidc"
            ]);
            $runtime = new RuntimeOptions([]);
            // 复制代码运行请自行打印 API 的返回值
            $result = $client->changeResellerConsumeAmountWithOptions($changeResellerConsumeAmountRequest, $runtime);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    /**
     * ===================================================================================
     * ======================================产品信息======================================
     */

    // 查询阿里云产品信息
    public function QueryProductList(){
        $client = self::createClient();
        $queryProductListRequest = new QueryProductListRequest([
            "pageNum" => 1,
            "pageSize" => 1000
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->queryProductList($queryProductListRequest);
        $result = $result->body->toMap();
        dump($result);die;
        if ($result['Code'] == 'Success') {
            $save_data = [];
            // dump($result['Data']['ProductList']['Product']);die;
            foreach ($result['Data']['ProductList']['Product'] as $k => $vo) {
                $code = $vo['ProductCode'];
                if ( empty($save_data[$code]) ) {

                    $save_data[$code] = [
                        'name'=>preg_replace('/(（|\().*?(）|\))/', '', $vo['ProductName']),
                        'code'=>$code,
                        'type'=>$vo['ProductType'],
                        'ctime'=>time()
                    ];
                }
            }
            if (!empty($save_data)) {
                Db::name('product')->insertAll($save_data);
            }
            
        }
    }

    /**
     * ===================================================================================
     * ======================================订单查询======================================
     */
    // 取消订单
    public function CancelOrder($orderId,$ower_id){
        $assume = $this->AssumeRole($ower_id);
        if ( $assume['status'] == 0 ) {
            return ['status'=>0,'msg'=>'获取AssumeRole异常'];
        }
        $assume = $assume['data'];
        $client = self::createClient($assume['AccessKeyId'],$assume['AccessKeySecret']);
        $options = ["orderId" => $orderId];
        $options['headers'] = ['x-acs-security-token'=>$assume['SecurityToken']];
        $cancelOrderRequest = new CancelOrderRequest($options);
        $runtime = new RuntimeOptions([]);
        try {
            $result = $client->cancelOrderWithOptions($cancelOrderRequest, $runtime);
            $result = $result->body->toMap();
            if (!$result['Success']) {
                return ['status'=>0,'msg'=>$result['Message']];
            }
            return ['status'=>1];
        }catch (Exception $e) {
           return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    // 查询预付费订单
    public function DescribeInstanceBill(){
        $client = self::createClient();
        $describeInstanceBillRequest = new DescribeInstanceBillRequest([
            "billingCycle" => "2022-01",
            "subscriptionType" => "Subscription",
            "maxResults" => 300,
            "billingDate" => "2022-01-30",
            "granularity" => "DAILY"
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->describeInstanceBill($describeInstanceBillRequest);
        $result = $result->body->toMap();
        dump($result);die;

    }

    // 订单详情查询服务
    public function GetOrderDetail($orderId,$ower_id=''){
        $options = ["orderId" => $orderId];
        if ( !empty($ower_id) ) {
            $assume = $this->AssumeRole($ower_id);
            if ( $assume['status'] == 0 ) {
                return ['status'=>0,'msg'=>'获取AssumeRole异常'];
            }
            $assume = $assume['data'];
            $options['headers'] = ['x-acs-security-token'=>$assume['SecurityToken']];
        }
        $client = self::createClient($assume['AccessKeyId'],$assume['AccessKeySecret']);
        $getOrderDetailRequest = new GetOrderDetailRequest($options);
        $result = $client->getOrderDetail($getOrderDetailRequest);
        $result = $result->body->toMap();
        if ($result['Success']) {
            return ['status'=>1,'data'=>$result['Data']['OrderList']['Order']];
        }else{
            return ['status'=>0];
        }
    }


    // 订单列表查询服务
    public function QueryOrders($ower_id='',$options=[]){
        if ( !empty($ower_id) ) {
            $assume = $this->AssumeRole($ower_id);
            if ( $assume['status'] == 0 ) {
                return ['status'=>0,'msg'=>'获取AssumeRole异常'];
            }
            $assume = $assume['data'];
            $options['headers'] = ['x-acs-security-token'=>$assume['SecurityToken']];
        }
        if (empty($options['createTimeStart'])) {
            $options['createTimeStart'] = "2016-05-23T13:00:00Z";
        }
        
        $client = self::createClient($assume['AccessKeyId'],$assume['AccessKeySecret']);

        $queryOrdersRequest = new QueryOrdersRequest($options);
        $result = $client->queryOrders($queryOrdersRequest);
        $result = $result->body->toMap();
        if ($result['Success']) {
            return ['status'=>1,'data'=>$result['Data']];
        }else{
            return ['status'=>0];
        }
    }

    // 获取预付费订单
    public function GetSubscriptionBill(){
        set_time_limit ( 0 );
        ini_set('memory_limit','10240M');
        
        $page_index = 1;
        $customers = [];
        $curtime = time();

        $products = Db::name('product')->field('code,discount')->select();
        $products  = arrayParamExtract($products ,'code','discount');
        do {
            $result = $this->QueryFusionOrderList($page_index);
            if ($result['status'] == 0) {
                break;
            }
            $list = $result['data'];
            foreach ($list['Data'] as $k => $vo) {
                if (time() - $curtime >= 1700) { // 设定运行时间为30分钟
                    exit();
                }
                
                // 如果订单已存在，则不再保存
                if ( !empty(BillModel::where('related_order_id',$vo['orderId'])->value('related_order_id')) ) {
                    continue;
                }
                $detail_result = $this->GetOrderDetail($vo['orderId'],$vo['endUserId']); // 获取订单详情
                if ( $detail_result['status'] == 0 ) {
                    continue;
                }
                // 含有后付费，不保存
                $subscription_types = array_column($detail_result['data'], 'SubscriptionType');
                if ( in_array('PayAsYouGo', $subscription_types) || !in_array('Subscription', $subscription_types) ) {
                    continue;   
                }
                // 含有非已支付订单，不保存
                $payment_status = array_column($detail_result['data'], 'PaymentStatus');
                $is_nopaid = 0;
                foreach ($payment_status as $ps_v) {
                    if ($ps_v != 'Paid') {
                        $is_nopaid = 1;
                        break;
                    }
                }
                if ( $is_nopaid == 1 ) {
                    continue;   
                }

                
                Db::startTrans();
                try {
                    $save_data = [];
                    foreach ($detail_result['data'] as $data) {
                        $data['InstanceIDs'] = json_decode($data['InstanceIDs'],true);
                        $tmp = [
                            'order_id'=>$data['RelatedOrderId'],
                            'aliyun_order_id'=>$data['RelatedOrderId'], // 用来区分是否提前获取的
                            'billing_cycle'=>date('Ymd',strtotime($vo['createTime'])),
                            // 'uid'=>$vo[''],
                            'ower_id'=>$vo['endUserId'],
                            'product_code'=>$data['ProductCode'],
                            'subscription_type'=>$data['SubscriptionType'],
                            'product_name'=>$vo['commodityName'],
                            'instance_id'=>$data['InstanceIDs'][0],
                            // 'tag'=>$vo[''],
                            // 'resource_group'=>$vo[''],
                            // 'solution_id'=>$vo[],
                            // 'solution_name'=>$vo[],
                            'region'=>$data['Region'],
                            'payment_time'=>strtotime($data['PaymentTime']),
                            'usage_start_time'=>timeDef(strtotime($data['UsageStartTime']),null,'Y-m-d H:i:s'),
                            'usage_end_time'=>timeDef(strtotime($data['UsageEndTime']),null,'Y-m-d H:i:s'),

                            'pretax_gross_amount'=>$data['PretaxGrossAmount'],
                            'invoice_discount'=>$data['PretaxGrossAmount'] - $data['PretaxAmount'],
                            'pretax_amount'=>$data['PretaxAmount'],

                            'currency'=>$data['Currency'],
                            
                            'related_order_id'=>$data['OrderId'],
                            'instance_config'=>$data['OriginalConfig'],
                            // 'instance_spec'=>$vo[''],
                            // 'public_ip'=>$vo[''],
                            // 'private_ip'=>$vo[''],
                            // 'zone'=>$vo[''],
                            // 'service_duration'=>$vo[''],
                            'order_type'=>$data['OrderType'],
                            'create_time'=>$curtime
                        ];
                        // $tmp = array_map('trim',$tmp); // 去除元素空格
                        
                        // 计算折扣
                        $ower_id = $tmp['ower_id'];
                        if ( !isset($customers[$ower_id]) ) {
                            $customer = Db::name('user')->field('id,total_discount,admin_id')->where('pk',$ower_id)->find();
                            if ( !empty($customer) && empty($customer['total_discount']) ) {
                                $customer['total_discount'] = 1;
                            }
                            $customers[$ower_id] = $customer;
                        }else{
                            $customer = $customers[$ower_id];
                        }
                        // 如果用户不存在，则不继续
                        if ( empty($customer) ) {
                            throw new \Exception("用户不存在");
                        }
                        if ( empty($customer['product'][$tmp['product_code']]) ) {
                            $user_discount = Db::name('user_discount')->where([
                                ['user_id','=',$customer['id']],
                                ['product','=',$tmp['product_code']]
                            ])->value('discount');
                            // 如果产品没设置折扣，则用总折扣
                            if ( empty($user_discount) ) {
                                $user_discount = $customer['total_discount'];
                            }
                            // 如果用户的折扣低于成本价，则按原价算
                            if ( $user_discount < emptyDef($products[$tmp['product_code']],1) ) {
                                $user_discount = 1;
                            }
                            $customer['product'][$tmp['product_code']] = $user_discount;
                            $customers[$ower_id] = $customer;
                        }

                        $tmp['admin_id'] = $customers[$ower_id]['admin_id'];
                        $tmp['user_discount'] = $customer['product'][$tmp['product_code']];
                        $tmp['platform_amount'] = round($tmp['pretax_gross_amount']*$tmp['user_discount'],4);
                
                        $save_data[] = $tmp;
                    }
                    if (empty($save_data)) {
                        throw new \Exception("无数据");
                    }

                    // 保存账单
                    if ( !Db::name('bill')->insertAll($save_data) ) {
                        throw new \Exception("账单生成失败");
                    }

                    // 计算差额
                    $difference = [];
                    foreach ($save_data as $difference_v) {
                        if (!empty($customer) && $customer['total_discount'] != $difference_v['user_discount']) {
                            $difference[] = round($difference_v['pretax_gross_amount'] * ($difference_v['user_discount'] - $customer['total_discount']),4);
                        }
                    }
 
                    // 保存收支明细
                    if ( !UserBillModel::saveData([
                        'user_id'=>$customer['id'],
                        'amount'=>-array_sum(array_column($save_data, 'platform_amount')),
                        'original'=>-array_sum(array_column($save_data, 'pretax_gross_amount')),
                        'type'=>0,
                        'remark'=>$save_data[0]['billing_cycle'].'预付费账单扣费，订单号：'.$save_data[0]['order_id'],
                        'difference'=>array_sum($difference)
                    ]) ) {
                        throw new \Exception("用户费用生成失败");
                    }

                    Db::commit();
                } catch (\Exception $e) {
                    // 更新失败 回滚事务
                    Db::rollback();
                    Db::name('test')->insert(['content'=>'预付费抓取异常：'.$e->getMessage()]);
                }
            }
            $page_index ++;
        } while ($list['PageNo'] * $list['PageSize'] < $list['Total']);

        return ['status'=>1];
    }

    // 虚商客户订单查询
    public function QueryFusionOrderList($page_index=1){
        $options = [
            // 'EndUserId' => '1578820813357913',
            // 'OrderId' => '219123270870354',

            'EndTime'=>date('Y-m-d'),
            'StartTime'=>date('Y-m-d'),
            // 'EndTime'=>'2022-11-30',
            // 'StartTime'=>'2022-11-01',
            'PageNo'=>$page_index,
            'PageSize'=>100
        ];

        try {
            self::accessKeyClient(); // 使用AK&SK初始化账号Client
            $result = AlibabaCloud::rpc()
                ->product('BssOpenApi')
                ->scheme('https') // https | http
                ->version('2021-06-09')
                ->action('QueryFusionOrderList')
                // ->method('GET')
                ->host('agency.aliyuncs.com')
                ->options(['query' => $options])
                ->request();

            $result = $result->toArray();
            // dump($result);die;
            return ['status'=>1,'data'=>$result];
        } catch (ClientException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        } catch (ServerException $e) {
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

   
}
